package admin;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import test.LocalProperties;


import com.objective.oji.OjiCatalogue;
import com.objective.oji.OjiDocVersion;
import com.objective.oji.OjiDocument;
import com.objective.oji.OjiException;
import com.objective.oji.OjiFolder;
import com.objective.oji.OjiLink;
import com.objective.oji.OjiObject;
import com.objective.oji.OjiPhysicalDocument;
import com.objective.oji.OjiPhysicalFile;
import com.objective.oji.OjiSearch;
import com.objective.oji.OjiTypeDefn;

public class Obj_API extends LocalObjSession {

    public Obj_API(LocalProperties AppProfile, SERVER_TYPE Selected_SERVER_PROFILE, LOGINMETHOD Login_Method_TYPE) {
	super(AppProfile, Selected_SERVER_PROFILE, Login_Method_TYPE);
    }

    public boolean createFolder() {
	try {

	    // Step 1: create a new OjiPhysicalDocument instance.
	    OjiFolder myFolder = apiSession.initFolder();
	    myFolder.create();

	    OjiFolder parent = (OjiFolder) apiSession.getObject("fA8501");
	    myFolder.setParent(parent);
	    myFolder.setNoteText("HELLO");
	    myFolder.setName("TEST3");
	    // newObject.setFieldValueByName(cat, "name", "blah blah blah");
	    myFolder.update();
	} catch (OjiException e) {
	    System.out.println("Exception - createFolder()");
	    e.printStackTrace();
	}
	return true;
    }

    public boolean createObject() {
	try {
	    OjiDocument newObject = apiSession.initDocument();
	    // OjiPhysicalDocument newObject =
	    // apiSession.initPhysicalDocument();
	    // OjiElectronicObject newObject =
	    // apiSession.initElectronicObject();
	    // OjiPhysicalFile newObject = apiSession.initPhysicalFile(0);
	    // OjiPhysicalObject newObject = apiSession.initPhysicalObject();
	    newObject.setDocumentPathOnCreation("C:\\TEMP\\obj1.txt");
	    OjiTypeDefn doc_type = (OjiTypeDefn) apiSession.getObject("dotdA9");
	    newObject.setTypeDefinition(doc_type);

	    // newObject.createNewVersionFromDisk("reason",
	    // "C:\\TEMP\\obj1.txt", 0, true );
	    OjiFolder parent = (OjiFolder) apiSession.getObject("fA8501");
	    newObject.setParent(parent);
	    newObject.create();

	    newObject.setName("new DIST doc1");
	    newObject.setNoteText("Here it goes");
	    newObject.update();
	} catch (OjiException e) {
	    System.out.println("Exception - createObject");
	    e.printStackTrace();
	}
	return true;
    }

    public boolean createObject3() {
	/*
	 * CREATE OBJECT 3 (TESTING STAGE) -------------------------
	 */
	try {
	    // Step 1: create a new OjiPhysicalDocument instance.
	    OjiPhysicalDocument newObject = apiSession.initPhysicalDocument();
	    // Step 2: fill in the characteristics of the new object.
	    newObject.setName("physical object created via the Java API");
	    newObject.setCommentText("comment text");
	    // OjiPhysicalFile parent = (OjiPhysicalFile)
	    // apiSession.getObject("fA8501");
	    // newObject.setParent(parent);
	    OjiFolder parent = (OjiFolder) apiSession.getObject("fA8501");
	    newObject.setParent(parent);

	    OjiCatalogue cat = (OjiCatalogue) apiSession.getObject("cA1");
	    newObject.setCatalogue(cat);
	    // newObject.setFieldValueByName(cat, "Legacy Project Number",
	    // "blah blah blah");

	    newObject.update();
	} catch (OjiException e) {
	    System.out.println("Exception - NewObject");
	    e.printStackTrace();
	}
	return true;
    }

    private String getDateString(String inDateString, long delta) {
	/*
	 * delta - (long) ( 1000 * 60 * 60 * 24 ) inDateString = "5 Dec 1999 00:07:21"
	 */
	SimpleDateFormat inDate_formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss", Locale.ENGLISH);
	SimpleDateFormat outDate_formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

	ParsePosition pos = new ParsePosition(0);
	Date baseTime = inDate_formatter.parse(inDateString, pos);

	Date date_modified = new Date(baseTime.getTime() + (long) (1000 * 60 * 60 * 24));
	return outDate_formatter.format(date_modified);
    }

    private void getFile(String objID, String docPath, String comment_note) throws OjiException {
	/*
	 * GET FILE --------------------
	 */
	OjiDocument doc = (OjiDocument) apiSession.getObject(objID);

	try {
	    // doc.setLinks(null); // release all links
	    doc.setNoteText("GetFile - TEST by Sonny");
	    // doc.update();

	    // OjiDocVersion docVer = doc.getVersion(2);
	    OjiDocVersion docVer = doc.getCurrentVersion();

	    System.out.println("Name:" + docVer.getDefaultLocalFileName());
	    System.out.println("ID:" + docVer.getObjId());
	    System.out.println("File Size:" + docVer.getFileSize());
	    System.out.println("File Type:" + docVer.getFileType());
	    System.out.println("Last Updated on :" + docVer.getDateUpdate());
	    System.out.println("Version:" + docVer.getVersionNumber());
	    String remoteFilePath = docPath + docVer.getDefaultLocalFileName();
	    docVer.getRemoteFile(remoteFilePath); // OVERWRITE if a same bane
	    // file exists

	    OjiPhysicalFile file = doc.getBelongingFile();
	    // file.getfgetFileSize
	    // OjiObjects aa = file.getContents();

	    /*
	     * Collection<OjiPhysicalFilePart> fileparts; fileparts = file.getFileParts();
	     * System.out.println(fileparts.size()); Iterator<OjiPhysicalFilePart> i =
	     * fileparts.iterator(); while
	     * (i.hasNext()) { OjiPhysicalFilePart filePart = i.next(); }
	     */

	} catch (OjiException e) {
	    System.out.println("Failed to create new version [" + objID + "]");
	    e.printStackTrace();
	}
    }


    public boolean getContent(String objID) {
	/*
	 * GEt File Content - retrieve content(s) ---------------------------
	 */

	OjiDocument myDoc = (OjiDocument) apiSession.getObject(objID);

	try {

	    OjiPhysicalFile myFile = myDoc.getBelongingFile();
	    myFile.update();

	    // OjiTypeDefn doc_type = (OjiTypeDefn )
	    // apiSession.getObject("duotA15");
	    // doc.setTypeDefinition(doc_type );
	    // doc.getFieldValue("Drawing Contents", "Admin");

	} catch (OjiException e) {
	    System.out.println("Failed to create new version for document [" + objID + "]");
	    e.printStackTrace();
	}
	return true;
    }

    public boolean getContents(String objID, String docPath, String comment_note) throws OjiException {

	getFile(objID, docPath, comment_note);

	OjiDocument doc = (OjiDocument) apiSession.getObject(objID);
	List<OjiLink> link_list = doc.getLinks();

	Iterator<OjiLink> it_links = link_list.iterator();
	while (it_links.hasNext()) {
	    OjiLink link = it_links.next();
	    OjiDocument obj = (OjiDocument) link.getLinkTarget();
	    System.out.println("Link Name:" + obj.getName());
	    System.out.println("Link getLinkTypeLabelForView:" + link.getLinkTypeLabelForView());
	    getFile(obj.getObjId(), docPath, comment_note);

	}
	return true;

    }
    public boolean getObjectAttr() {
	OjiFolder myFolder = (OjiFolder) apiSession.getObject("fA8501");
	System.out.println("Object name is " + myFolder.getName() + myFolder.getFieldValueByName("name"));
	return true;
    }

    public boolean setObjectAttr(String object_id, String attr, String value) {

	try {

	    OjiDocument myDoc = (OjiDocument) apiSession.getObject(object_id);
	    System.out.println(object_id + "," + myDoc.getName());

	    List<String> str_list = new ArrayList<String>();

	    String single_attr1 = "Line 1";
	    String single_attr2 = "Line 2"; // "Document Type";
	    // System.out.println("> Single Attr1 : " +
	    // myDoc.getFieldValueByName(single_attr1));
	    // System.out.println("> Single Attr2 : " +
	    // myDoc.getFieldValueByName(single_attr2));

	    String multi_attr1 = "Drawing Contents";
	    // str_list = myDoc.getFieldValues(multi_attr1);
	    // str_list = myDoc.getFieldValuesByName(multi_attr1);
	    str_list = myDoc.getFieldValues(multi_attr1);
	    // myDoc.get
	    // ObjCatalogableObject
	    if (str_list.isEmpty()) {
		System.out.println("LIST IS EMPTY");
	    } else {
		// com.objective.objapi.ObjApiMultiValuedField multivalue =
		// str_list.get(0);
		String multivalue = str_list.get(0);
		System.out.println("Attr2[0] 	  - ");

	    }

	    myDoc.setFieldValueByName(attr, value);
	    // myDoc.setFieldValue("Drawing Template (Dist)", value)
	    // myDoc.setFieldValue(attr, value);
	    // myDoc.setNoteText("TEST by Sonny");
	    // myDoc.setName("TEST3");

	    myDoc.update();
	} catch (OjiException e) {
	    System.out.println("Exception - setObjectAttr()");
	    System.err.println("Error: " + e.getMessage());
	    e.printStackTrace();

	}
	// myFolder.update();
	return true;
    }

    public boolean Search(String type) {
	/*
	 * SEARCH extended --------------------------- Find group(s) where the user is belonged
	 */

	try {
	    OjiSearch newSearch = apiSession.initAdvancedSearch();
	    OjiTypeDefn search_type = apiSession.getTypeDefnByName("alias");

	    newSearch.setObjectSearchType(search_type);
	    newSearch.addCriteria("parent group", "is", "gA25", 0, 0, OjiSearch.AND_RELATION);
	    newSearch.execute();

	    Collection<OjiObject> results = newSearch.getResults();
	    Iterator<OjiObject> i = results.iterator();
	    System.out.println("SEARCH: Type is " + search_type.getSingularName());

	    while (i.hasNext()) {
		OjiObject searchResult = i.next();
		String alias_name = searchResult.getLabelForView();
		String user_name = alias_name.replace(" alias", "");
		System.out.println("SEARCH: " + user_name);
	    }
	} catch (OjiException e) {
	    System.out.println("FAILED");
	    e.printStackTrace();
	}
	return true;

    }

    public boolean Revert(String objID, String comment_note) {

	/*
	 * REVERT OPERATION ---------------------------
	 */

	OjiDocument mydoc = (OjiDocument) apiSession.getObject(objID);
	// OjiInternetLink doc_link =
	// (OjiInternetLink)apiSession.getObject(objID);

	try {
	    mydoc.revertVersion();
	    mydoc.update();

	} catch (OjiException e) {
	    System.out.println("Failed to REVERT - document [" + objID + "]");
	    e.printStackTrace();
	}
	return true;
    }

    /**
     * @param objID
     * @param fileName
     * @param comment_note
     */

    public boolean saveNewVersion_with_Unlink(String objID, String fileName, String comment_note) {
	/*
	 * SAVE AS NEW VERSION -------------------- doc.createNewVersionFromDisk (comment_note,
	 * fileName, 0, true);
	 * doc.createNewVersion (comment_note, fileName);
	 */

	OjiDocument doc = (OjiDocument) apiSession.getObject(objID);

	try {
	    doc.setLinks(null); // release all links
	    doc.setNoteText("All the links are removed. TEST by Sonny");
	    doc.update();

	    OjiDocVersion docVers = doc.createNewVersion("", null);
	    docVers.release(comment_note, fileName, 0, false);

	} catch (OjiException e) {
	    System.out.println("Failed to create new version [" + objID + "]");
	    e.printStackTrace();
	}
	return true;
    }
}
